package com.eternal.base.data.ble;

import com.eternal.base.database.entity.History;
import com.eternal.base.protocol.ProtocolResolution;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class HistoryParse extends BaseParse<History> {
    private byte packetSize;
    private int historySize;
    private long start;
    private long time;

    public HistoryParse(long time) {
        this.time = time;
    }

    boolean checkLength() {
        return i + packetSize < now.length;
    }

    History parse() {
        History result = ProtocolResolution.parseHistory(now, i, start/60*60, packetSize == 4);
        start += historySize;
        --total;
        i += packetSize;
        return result;
    }

    void init() {
        if (now[18] == 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(now[19], now[20], now[21], now[22], now[23], now[24]);
            start = (int) (calendar.getTimeInMillis() / 1000);
        } else {
            start = ((now[19] & 0xff) << 24) | ((now[20] & 0xff) << 16) |
                    ((now[21] & 0xff) << 8) | (now[22] & 0xff);
            start= (int) (TimeUnit.MILLISECONDS.toSeconds(time)-start);
        }
        historySize = ((now[25] & 0xff) << 8) | (now[26] & 0xff);
        total = now[27];
        if (now[28] == 2) {
            packetSize = 4;
        } else {
            packetSize = 5;
        }
        i = 29;
    }
}
